package com.lzx.adx.report.biz;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayDataDataserviceAdConversionUploadModel;
import com.alipay.api.domain.ConversionData;
import com.alipay.api.request.AlipayDataDataserviceAdConversionUploadRequest;
import com.alipay.api.response.AlipayDataDataserviceAdConversionUploadResponse;
import com.google.common.collect.Lists;
import com.lzs.adx.commmon.utils.DateUtils;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.OcpxAccountLocalCache;
import com.lzx.adx.report.cache.ProductLimitLocalCache;
import com.lzx.adx.report.dto.*;

import com.lzx.adx.report.service.OrderRecodService;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.service.WphOrderService;
import com.lzx.adx.report.support.context.v3.CallBackV3Context;
import com.lzx.adx.report.support.strategy.v3.media.AbstractChannel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Component
@Slf4j
public class HwWphBiz {



    @Autowired
    private ReportService reportService;


    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;

    @Resource
    private WphOrderService wphOrderService;

    @Resource
    private CallBackV3Context callBackV3Context;


    @Resource
    private OrderRecodService orderRecodService;


    /**
     * 唯品会的CPS结果回调给华为
     * @param wphOrderDTO
     * @return
     */
    public void callBackUrl(WphOrderDTO wphOrderDTO) throws AlipayApiException {
        log.info("接收了唯品会的回调，请求的参数为{}",JsonUtils.toJsonString(wphOrderDTO));

        //无数据的不处理了
        if(Objects.isNull(wphOrderDTO)){
            log.info("无数据，不处理了");
            //无数据，不处理了
            return ;
        }

        //如果是付费订单，判断是否已经做过推送了
        Map<String,Object> params=new HashMap<>();
        params.put("id",wphOrderDTO.getOrderSn());
        List<OrderRecodDTO> list = orderRecodService.list(params);
        if(CollectionUtil.isNotEmpty(list)){
            //已处理的不在推送了
            return ;
        }

        //失效就添加到入库里面
        if(wphOrderDTO.getStatus().equals(3)){
            log.info("订单号已失效了 {}",wphOrderDTO.getOrderSn());
            //处理入库
            OrderRecodDTO orderRecodDTO=new OrderRecodDTO();
            orderRecodDTO.setOrderSn(wphOrderDTO.getOrderSn());
            orderRecodDTO.setCreateTime(new Date());
            orderRecodService.save(orderRecodDTO);
            return;
        }

        //小于今天就把它添加到入库记录里
        if(DateUtils.isDateBeforeToday(wphOrderDTO.getOrderTime())){
            String format = DateUtils.format(wphOrderDTO.getOrderTime(), "yyyy-MM-dd HH:mm:ss");
            log.info("订单号已比当前时间小， {}， 时间为{}",wphOrderDTO.getOrderSn(),format);
            //处理入库
            OrderRecodDTO orderRecodDTO=new OrderRecodDTO();
            orderRecodDTO.setOrderSn(wphOrderDTO.getOrderSn());
            orderRecodDTO.setCreateTime(new Date());
            orderRecodService.save(orderRecodDTO);
            return;
        }


        //不是付费订单不处理
        if(!wphOrderDTO.getStatus().equals(6)){
            log.info("订单号为{}，订单状态{}，不做转化回传",wphOrderDTO.getOrderSn(),wphOrderDTO.getStatus());
            //无数据，不处理了
            return ;
        }


        //获取账户的配置
        OcpxAccountDTO accountDTO = OcpxAccountLocalCache.getInstance().get(wphOrderDTO.getChannelTag());

        if(Objects.isNull(accountDTO)){
            log.info("渠道号为{}, 未配置账户信息{}",wphOrderDTO.getChannelTag());
            return;
        }

        //下单时间
        String orderTime= DateUtil.format(wphOrderDTO.getOrderTime(),"yyyyMMddHH");
        //取出最新的一条报文来上报
        ReportDTO reportDTO= reportService.getNewData(accountDTO.getId(),orderTime,wphOrderDTO);
        if(Objects.isNull(reportDTO)){
            log.info("订单号为{} ，没有匹配合适的点击",wphOrderDTO.getOrderSn());
            return;
        }
        ProductLimitLocalCache instance = ProductLimitLocalCache.getInstance();

        //价格别
        String price = instance.get(accountDTO.getProductChannel());
        String orderCommonPrice = wphOrderDTO.getEstiCommAmountAfterDeduction().toPlainString();
        log.info("订单号为{} ，来源于产品{} 配置的金额{}，订单金额{}", wphOrderDTO.getOrderSn(), accountDTO.getProductChannel(), price, orderCommonPrice);
        reportDTO.setSid(wphOrderDTO.getOrderSn());

        if(StringUtils.isBlank(price)){
            String defaultKey = accountDTO.getDefaultKey();
            String time = String.valueOf(System.currentTimeMillis());
            AbstractChannel abstractReport = callBackV3Context.getCallBack(accountDTO.getMediaChannel());
            abstractReport.callback(reportDTO, accountDTO, defaultKey, time);
        }else{
            BigDecimal bigDecimal = new BigDecimal(price);
            //当拥挤大于配置的金额，才需要回调
            if (wphOrderDTO.getEstiCommAmountAfterDeduction().compareTo(bigDecimal) > 0) {
                String defaultKey = accountDTO.getDefaultKey();
                String time = String.valueOf(System.currentTimeMillis());
                AbstractChannel abstractReport = callBackV3Context.getCallBack(accountDTO.getMediaChannel());
                abstractReport.callback(reportDTO, accountDTO, defaultKey, time);
            }
        }

        OrderRecodDTO orderRecodDTO=new OrderRecodDTO();
        orderRecodDTO.setOrderSn(wphOrderDTO.getOrderSn());
        orderRecodDTO.setCreateTime(new Date());
        orderRecodService.save(orderRecodDTO);

    }



}
